package rhc.taskSchedule.taskSchedule.schedule.schedule;

import java.util.List;

import org.springframework.stereotype.Service;

import rhc.taskSchedule.commander.TaskScheduleCommanderExecute;
import rhc.taskSchedule.entity.Running;
import rhc.taskSchedule.entity.RunningStartType;
import rhc.taskSchedule.entity.RunningType;
import rhc.taskSchedule.exception.ScheduleException;
import rhc.taskSchedule.taskDistribute.TaskDistribute;

@Service
public class TaskScheduleImpl extends BasicTaskScheduleImpl {

	public TaskScheduleImpl(String taskScheduleId,TaskScheduleCommanderExecute taskScheduleCommanderExecute) throws Exception {
		super(taskScheduleId,taskScheduleCommanderExecute);
	}

	@Override
	public void run() throws Exception {
		
		Exception exception=null;
		try{
			List<String> taskIdList=taskSchedule.getTaskList();
			
			if(null == taskIdList || taskIdList.isEmpty()){
				throw new ScheduleException("运行 {} 没有包含任务",runningId);
			}
			for(String taskId:taskIdList){
				try{
					distributeTask(taskId);
				}catch(Exception e){
					logger.error("调度 "+runningId+" 分发任务 "+taskId+" 出错，"+e.getMessage());
					e.printStackTrace();
				}
			}
		}catch(Exception e){
			exception=e;
		}finally{
			if(null == exception){
				super.beginRun();
			}else{
				throw new ScheduleException("启动调度 {} 出错",scheduleId);
			}
		}
	}

	@Override
	public void stop() throws Exception {
		super.stopRun();
		
	}

	@Override
	public void pause() throws Exception {
		throw new ScheduleException("调度不支持暂停操作");
	}

	@Override
	public void regain() throws Exception {
		throw new ScheduleException("调度不支持恢复操作");
	}

	/**分发任务
	 * @param taskId
	 * @throws Excpetion
	 */
	private void distributeTask(String taskId) throws Exception{
		TaskDistribute taskDistribute=taskScheduleCommanderExecute.getTaskDistribute();
		
		Running running=taskDistribute.createRunning(taskId, RunningType.TASK, RunningStartType.SCHEDULE);
		
		taskDistribute.startRunning(running.getId());
	}

	@Override
	public void error() throws Exception {
		super.errorRun(null);
	}
	
}
